
public class p1007_1157ms_33th {

	public static//
	// -----
	// -----
	class Main {
		public static void main(String[] args) throws Exception {
			java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
			String[] parts = reader.readLine().split(" ");
			int m = Integer.parseInt(parts[1]);
			Object[][] list = new Object[m][];
			for (int i = 0; i < m; i++) {
				String line = reader.readLine();
				list[i] = new Object[] { count(line), line };
			}
			java.util.Arrays.sort(list, new java.util.Comparator<Object[]>() {
				public int compare(Object[] o1, Object[] o2) {
					return (Integer) o1[0] - (Integer) o2[0];
				}
			});
			for (Object[] entry : list)
				System.out.println((String) entry[1]);
		}

		static int count(String line) {
			int a = 0, c = 0, g = 0, sum = 0;
			for (int i = line.length() - 1; i >= 0; i--) {
				char x = line.charAt(i);
				if (x == 'A') {
					a++;
				} else if (x == 'C') {
					c++;
					sum += a;
				} else if (x == 'G') {
					g++;
					sum += a + c;
				} else {
					sum += a + c + g;
				}
			}
			return sum;
		}

	}

	// -----
	// -----

	public static void main(String[] args) throws Exception {
		Judge.run();
	}

}
